package ua.exchangeratesukraine.ui.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import ua.exchangeratesukraine.R;
import ua.exchangeratesukraine.adapter.BanksAdapter;
import ua.exchangeratesukraine.model.CurrencyModel;
import ua.exchangeratesukraine.util.Constants;
import ua.exchangeratesukraine.util.DataTask;
import ua.exchangeratesukraine.util.Util;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class FragmentBanks extends FragmentBase {

	private final String		LOG_TAG				= getClass().getSimpleName();
	private String[]			currencyTypeArray	= null;
	private String[]			currencyCodeArray	= null;
	private String[]			bankCodes			= null;
	private String[]			bankNames			= null;
	private List<String>		bankNamesOrig		= new ArrayList<String>();
	private String				currencyCode		= "";
	private String				URL_BANKS			= "";
	private String				bankName			= "";
	private String				bankCode			= "";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {

		View view = inflater.inflate(R.layout.fragment_banks, null);

		currencyTypeArray = getActivity().getResources().getStringArray(R.array.currency_type);
		currencyCodeArray = getActivity().getResources().getStringArray(R.array.currency_type_code);

		listHeader = inflater.inflate(R.layout.list_header_banks, null);
		listFooter = inflater.inflate(R.layout.list_footer, null);
		tvCurrentDate = (TextView) view.findViewById(R.id.tvCurrentDate);
		btnResult = (Button) view.findViewById(R.id.btnResult);
		tvSetBank = (TextView) view.findViewById(R.id.tvSetBank);
		tvDate = (TextView) view.findViewById(R.id.tvDate);
		bar = (ProgressBar) view.findViewById(R.id.progressBar);
		bar.setVisibility(View.INVISIBLE);
		tvCurrentDate.setOnClickListener(this);
		tvSetBank.setOnClickListener(this);
		tvCurrentDate.setOnTouchListener(this);
		tvSetBank.setOnTouchListener(this);
		btnResult.setOnClickListener(this);
		btnResult.setOnTouchListener(this);

		// Adapter
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, R.layout.spinner_item,
				currencyTypeArray);
		adapter.setDropDownViewResource(R.layout.spinner_item_dropdown);

		Spinner currencySpinner = (Spinner) view.findViewById(R.id.currencySpinner);
		currencySpinner.setAdapter(adapter);

		// click listener for spinner
		currencySpinner.setOnItemSelectedListener(this);

		return view;
	}

	@Override
	public void onActivityCreated(Bundle inState) {
		super.onActivityCreated(inState);

		date = getCurrentDate();
		bankCodes = getResources().getStringArray(R.array.bank_codes);
		bankNames = getResources().getStringArray(R.array.bank_names);
		
		Log.d(LOG_TAG, "bankNames size : " + bankNames.length + " ; bankCodes size: " + bankCodes.length);
		for (int i = 0; i < bankCodes.length; i++) {
			Log.d(LOG_TAG, "" + bankNames[i] + " : " + bankCodes[i]);
		}
		
		bankNamesOrig = Arrays.asList(getResources().getStringArray(R.array.bank_names_orig));
		bankName = bankNames[0];

		if (inState != null) {

			date = inState.getString(Constants.DATE);
			isListShow = inState.getBoolean(Constants.IS_LIST_SHOW);
			isDialogShow = inState.getBoolean(Constants.IS_DIALOG_SHOW);
			bankName = inState.getString(Constants.BANK_NAME);
			bankCode = inState.getString(Constants.BANK_CODE);
			currencyModelArray = inState.getParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY);

			if (isListShow) {
				setListHeader(listHeader);
				getListView().addFooterView(listFooter);
			}

			if (adapter == null) {
				adapter = getAdapter();
			}
			setListAdapter(adapter);
			if (isDialogShow) {
				showBankDialog();
			}
			fillTvDate(" " + getString(R.string.text_on_date) + " " + date);
		}
		tvSetBank.setText(bankName);
		fillTvCurrentDate(date);
	}

	private void showBankDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(R.string.bank_dialog_text);
		builder.setItems(bankNames, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int pos) {
				bankCode = bankCodes[pos];
				bankName = bankNames[pos];
				Log.d(LOG_TAG, "bankName : " + bankName + " ; bankCode : " + bankCode + "\n");
				tvSetBank.setText(bankName);
				isDialogShow = false;
			}
		});
		builder.show();
		isDialogShow = true;
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		// display selected item position
		String currencyText = parent.getSelectedItem().toString();
		for (int i = 0; i < currencyTypeArray.length; i++) {
			if ((parent.getSelectedItem().toString()) == currencyTypeArray[i]) {
				currencyCode = currencyCodeArray[i];
			}
		}
		Log.d(LOG_TAG, "currencyText : " + currencyText + ", currencyCode : " + currencyCode);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.tvCurrentDate:
				showDateDialog();
				break;
			case R.id.tvSetBank:
				showBankDialog();
				break;
			case R.id.btnResult:
				isNetworkAvailable = Util.isNetworkAvailable(context);
				if (!isNetworkAvailable) {

					showToast(getString(R.string.title_toast_connection_error),
							getString(R.string.text_toast_connection_error));
					return;
				}

				boolean isTimeFuture = Util.isTimeFuture(date);
				if (isTimeFuture) {
					showToast(getString(R.string.title_toast_attention),
							getString(R.string.text_day_no_present));
					return;
				}

				boolean isDayOff = Util.isDayOff(holidayMonthArray, holidayDayArray, date);
				if (isDayOff) {
					showToast(getString(R.string.title_toast_attention), getString(R.string.text_day_off));
					return;
				}

				URL_BANKS = BASE_URL + "/kursy-valut/cash_xml/?id=" + WEB_ID + "&currency=" + currencyCode
						+ "&date=" + date + "&bank=" + bankCode;
				Log.d(LOG_TAG, "Date on click : " + date);
				Log.d(LOG_TAG, "URL_BANKS : " + URL_BANKS);

				DataTask mTask = new DataTask(context, this);
				mTask.execute(URL_BANKS);
				break;
			default:
				break;
		}
	}

	protected BanksAdapter getAdapter() {
//		int i = 0;
//		if(!Locale.getDefault().equals("ru_RU")){
//			for (CurrencyModel currencyModel : currencyModelArray) {
//				for (String bankName2 : bankNamesOrig) {
//					if(currencyModel.getName().equals(bankName2))
//						currencyModel.setName(bankNames[i]);
//				}
//				i++;
//			}
//		}
		return new BanksAdapter(context, currencyModelArray, bankCodes, bankNames);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {

		outState.putBoolean(Constants.IS_LIST_SHOW, isListShow);
		outState.putBoolean(Constants.IS_DIALOG_SHOW, isDialogShow);
		outState.putString(Constants.DATE, date);
		outState.putString(Constants.BANK_NAME, bankName);
		outState.putString(Constants.BANK_CODE, bankCode);
		outState.putString(Constants.BANK_NAME_CURRENT, bankName);
		outState.putParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY, currencyModelArray);

		super.onSaveInstanceState(outState);
	}
	
	@Override
	public void sort(final View view, boolean isRequest) {
		if (!currencyModelArray.isEmpty() && view != null) {
			if (isRequest) {
				touchUnitCount = 0;
				touchBuyCount = 0;
				touchSaleCount = 0;
				touchAbsBuyCount = 0;
				touchAbsSaleCount = 0;
				touchRelBuyCount = 0;
				touchRelSaleCount = 0;
			}
			switch (view.getId()) {
				case R.id.tvNameCurrencyUnit: 	touchUnitCount++; 		break;
				case R.id.tvNameRateBuy:  		touchBuyCount++;	 	break;
				case R.id.tvNameRateSale:  		touchSaleCount++;	 	break;
				case R.id.tvNameChangeAbsBuy:  	touchAbsBuyCount++;	 	break;
				case R.id.tvNameChangeAbsSale:  touchAbsSaleCount++;	break;
				case R.id.tvNameChangeRelBuy:  	touchRelBuyCount++;	 	break;
				case R.id.tvNameChangeRelSale:  touchRelSaleCount++;	break;
				default:												break;
			}
			if (Locale.getDefault().toString().equals("uk_UA")) {
				for (CurrencyModel currencyModel : currencyModelArray) {
					char[] name = currencyModel.getName().toCharArray();
					if (name[0] == Constants.SYMBOL_UKR_E ){
						name[0] = Constants.SYMBOL_RUS_E;
						currencyModel.setName(String.valueOf(name));
					}
					if (name[0] == Constants.SYMBOL_UKR_I ){
						name[0] = Constants.SYMBOL_RUS_I;
						currencyModel.setName(String.valueOf(name));
					}
				}
			}
			Collections.sort(currencyModelArray, new Comparator<CurrencyModel>() {
				public int compare(CurrencyModel s1, CurrencyModel s2) {
					switch (view.getId()) {
						case R.id.tvNameCurrencyUnit:
							if(touchUnitCount % 2 == 0)   return s2.getName().compareTo(s1.getName());
							else 					   	  return s1.getName().compareTo(s2.getName()); 
						case R.id.tvNameRateBuy:
							if(touchBuyCount % 2 == 0) 	  return (Double.valueOf(s2.getBuy()).compareTo(
																  Double.valueOf(s1.getBuy()))); 
							else 						  return (Double.valueOf(s1.getBuy()).compareTo
									  							 (Double.valueOf(s2.getBuy()))); 
						case R.id.tvNameRateSale:
							if(touchSaleCount % 2 == 0)   return (Double.valueOf(s2.getSale()).compareTo(
																  Double.valueOf(s1.getSale()))); 
							else 						  return (Double.valueOf(s1.getSale()).compareTo
																 (Double.valueOf(s2.getSale()))); 
						case R.id.tvNameChangeAbsBuy:
							if(touchAbsBuyCount % 2 == 0) return  Double.valueOf(s2.getBuyChangeAbs()).compareTo
									 							 (Double.valueOf(s1.getBuyChangeAbs()));
							else 						  return  Double.valueOf(s1.getBuyChangeAbs()).compareTo
		 														 (Double.valueOf(s2.getBuyChangeAbs()));
						case R.id.tvNameChangeAbsSale:
							if(touchAbsSaleCount % 2 == 0)return  Double.valueOf(s2.getSaleChangeAbs()).compareTo
															 	 (Double.valueOf(s1.getSaleChangeAbs()));
							else 						  return  Double.valueOf(s1.getSaleChangeAbs()).compareTo
									 							 (Double.valueOf(s2.getSaleChangeAbs()));
						case R.id.tvNameChangeRelBuy:
							if(touchRelBuyCount % 2 == 0) return  Double.valueOf(s2.getBuyChangeRel()).compareTo
																 (Double.valueOf(s1.getBuyChangeRel()));
							else 						  return  Double.valueOf(s1.getBuyChangeRel()).compareTo
																 (Double.valueOf(s2.getBuyChangeRel()));
						case R.id.tvNameChangeRelSale:
							if(touchRelSaleCount % 2 == 0)return  Double.valueOf(s2.getSaleChangeRel()).compareTo
																 (Double.valueOf(s1.getSaleChangeRel()));
							else 						  return  Double.valueOf(s1.getSaleChangeRel()).compareTo
																 (Double.valueOf(s2.getSaleChangeRel()));
						default:break;
					}
					return 0;
				}
			});
			if (Locale.getDefault().toString().equals("uk_UA")) {
				for (CurrencyModel currencyModel : currencyModelArray) {
					char[] name = currencyModel.getName().toCharArray();
					if (name[0] == Constants.SYMBOL_RUS_E ){
						name[0] = Constants.SYMBOL_UKR_E;
						currencyModel.setName(String.valueOf(name));
					}
					if (name[0] == Constants.SYMBOL_RUS_I ){
						name[0] = Constants.SYMBOL_UKR_I;
						currencyModel.setName(String.valueOf(name));
					}
				}
			}
		}
		initArray(currencyModelArray);
	}
	@Override
	protected void setBanksName(ArrayList<CurrencyModel> currencyModelArray) {
		
		String[] bankNamesOrig	= getActivity().getResources().getStringArray(R.array.bank_names_orig);
		String[] bankNamesSet	= getActivity().getResources().getStringArray(R.array.bank_names_set);
		for (CurrencyModel currencyModel : currencyModelArray) {
			for (int i = 0; i < bankNamesOrig.length; i++) {
				if(currencyModel.getName().equalsIgnoreCase(bankNamesOrig[i]))
					currencyModel.setName(bankNamesSet[i]);
			}
		}
	}

}